Dashboard Temp Share Shortlinks Frames API

HTMLify

Koko Eating Bananas.py
Views: 17 | Author: prakhardoneria
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import math

class Solution:
    def kokoEat(self, arr, k):
        # The minimum possible speed is 1
        # The maximum speed needed is the size of the largest pile
        low = 1
        high = max(arr)
        ans = high
        
        while low <= high:
            mid = (low + high) // 2
            
            # Calculate total hours needed at speed 'mid'
            total_hours = 0
            for pile in arr:
                # math.ceil(pile / mid) alternative without floats:
                total_hours += (pile + mid - 1) // mid
            
            if total_hours <= k:
                # Koko can finish, try to find a slower (smaller) speed
                ans = mid
                high = mid - 1
            else:
                # Too slow, must increase the speed
                low = mid + 1
                
        return ans